package com.jiankangjin.appspos.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.stereotype.Service;

import com.jiankangjin.appspos.requestparam.object.Goods;
import com.jiankangjin.appspos.responsparam.object.ResponseDiag;
import com.jiankangjin.appspos.responsparam.object.ResponseGoods;
import com.jiankangjin.appspos.services.OrderServieces;
import com.jiankangjin.appspos.util.ResourceMap;
import com.jiankangjin.appspos.vo.AllowRefundVo;
import com.jiankangjin.appspos.vo.CreateOrderVo;
import com.jiankangjin.appspos.vo.CreateRefundVo;
import com.jiankangjin.appspos.vo.GetOrderResultVo;
import com.jiankangjin.appspos.vo.GetPayStatusVo;
import com.jiankangjin.appspos.vo.PayOrderVo;
import com.jiankangjin.appspos.vo.SearchOrderVo;
import com.jiankangjin.appspos.vo.UpdOrderInfoVo;
import com.jiankangjin.appspos.vo.UpdOrderInfoVo.Trade;
import com.jiankangjin.common.json.jackson.JSONUtil;
import com.jiankangjin.httpclient.HttpClient;


@Service
public class OrderServicesImpl implements OrderServieces {
	private static final transient Log logger = LogFactory.getLog(OrderServicesImpl.class);
	
	/**
	 * 创建订单
	 */
	@Override
	public CreateOrderVo createOrder(String merchId, String merchName,
			String merchantOrderId, int totalFee, String currency,
			String content, String detailJSON, boolean isTip, String buyerName,
			String buyerCellphone, String comment,  String busi_type, String operatorId,
			String operatorName, String orderTotalFee, String discountFee,
			String discountComment, String localPaySsn, int fee,
			String channelId, String buyerToken, String buyerVoucher,
			String channelType) {
		CreateOrderVo createOrderVo = new CreateOrderVo();
		try {
			List<Goods> goods = new ArrayList<Goods>();
			goods = JSONUtil.fromJSON(detailJSON, new TypeReference<List<Goods>>(){});
			List<ResponseGoods> goods_detail = new ArrayList<ResponseGoods>();
			for (int i = 0; i < goods.size(); i++) {
				ResponseGoods detail = new ResponseGoods();
				detail.setGoods_type(goods.get(i).getGoods_type());
				detail.setGoods_id(goods.get(i).getGoods_id());
				detail.setGoods_name(goods.get(i).getGoods_name());
				detail.setStd(goods.get(i).getStd());
				detail.setGoods_quantity(goods.get(i).getGoods_quantity());
				detail.setGoods_price(goods.get(i).getGoods_price());
				detail.setGoods_url(goods.get(i).getGoods_url());
				goods_detail.add(detail);
			}
			ResponseDiag diag_detail  = new ResponseDiag("9527", "上海左岸私立医院", "250", "感冒发烧", "国外先进技术");
			List<ResponseDiag> a = new ArrayList<ResponseDiag>();
			a.add(diag_detail);
			a.add(diag_detail);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("module_id", "app001");
			params.put("version", "v0.0.1");
			params.put("sign", "appSPOS_createOrder_sign");
			params.put("merchant_order_id", merchantOrderId);

            // 查询商户得出的动态信息
			params.put("merchant_id", merchId);
			params.put("store_name", merchName);

			params.put("total_fee", totalFee);
			params.put("currency", currency);
			params.put("content", content);
			params.put("goods_count", goods.size());
			params.put("goods_detail", goods_detail.toString());
			params.put("diag_detail", a.toString());
			params.put("is_tip", isTip);
			params.put("buyer_name", buyerName);
			params.put("buyer_cellphone", buyerCellphone);
			params.put("page_callback", "http_callback_html");
			params.put("order_callback", "http_callback_html");
			params.put("comment", comment);
			params.put("busi_type", busi_type);
			params.put("operator_id", operatorId);
			params.put("operator_name", operatorName);
			params.put("order_total_fee", orderTotalFee);//订单总额-折扣金额=订单金额(订单表中的ordAmt)
			params.put("discount_fee", discountFee);
			params.put("discount_comment", discountComment);
			params.put("local_pay_ssn", localPaySsn);//支付的参数
			params.put("fee", fee);
			params.put("channel_id", channelId);
			params.put("buyer_token", buyerToken);
			params.put("buyer_voucher", buyerVoucher);
			params.put("channel_type", channelType);
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统创建订单:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/create_order", params);
			if (logger.isInfoEnabled()) {
				logger.info("交易系统创建订单返回:" + map);
			}
			if(map == null) {
				createOrderVo.setResp_status("9999");
				createOrderVo.setMsg("交易系统创建订单返回空");
				return createOrderVo;
			}
			String[] resTip = ResourceMap.getArray("T_create_order_" + (String) map.get("resp_status"));
			createOrderVo.setResp_status(resTip[0]);
			createOrderVo.setMsg(resTip[1]);
			@SuppressWarnings("unchecked")
			Object o = (List<Map<String,String>>)JSONUtil.fromJSON((String)map.get("channel"), List.class);
			createOrderVo.setChannel(o);
			createOrderVo.setOrder_id((String)map.get("order_id"));
			createOrderVo.setSign("appSPOS_createOrder_sign");
			return createOrderVo;
		} catch (Exception e) {
			logger.error(this, e);
			return createOrderVo;
		}
	}

	/**
	 * 订单支付
	 */
	@Override
	public PayOrderVo payOrder(String token, String localPaySsn,
			String orderId, int fee, String currency, String channelId,
			String buyerToken, String buyerVoucher, String channelType) {
		PayOrderVo payOrderVo=new PayOrderVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("module_id", "app001");
			params.put("version", "v0.0.1");
			params.put("sign", "payOrder-sign");
			params.put("local_pay_ssn", localPaySsn);
			params.put("order_id", orderId);
			params.put("fee", ""+fee);
			params.put("currency", currency);
			params.put("channel_id", channelId);
			params.put("buyer_token", buyerToken);
			params.put("buyer_voucher", buyerVoucher);
			params.put("channel_type", channelType);
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统订单支付:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/pay_order",params);
			if (logger.isInfoEnabled()) {
				logger.info("交易系统订单支付返回:" + map);
			}
			if(map == null) {
				payOrderVo.setResp_status("9999");
				payOrderVo.setMsg("交易系统订单支付返回空");
				return payOrderVo;
			}
			String[] resTip = ResourceMap.getArray("T_pay_order_" + (String) map.get("resp_status"));
			payOrderVo.setResp_status(resTip[0]);
			payOrderVo.setMsg(resTip[1]);
			payOrderVo.setSub_deal_ssn((String)map.get("sub_deal_ssn"));
			payOrderVo.setSub_deal_stauts((String)map.get("sub_deal_stauts"));
			payOrderVo.setSign("payorder_appSPOS_sin");
			return payOrderVo;
		} catch (Exception e) {
			logger.error(this, e);
			return payOrderVo;
		}
	}

	/**
	 * 获取订单支付状态
	 */
	@Override
	public GetPayStatusVo getPayStatus(String token, String subDealSsn,
			String orderId) {
		GetPayStatusVo getPayStatusVo = new GetPayStatusVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("module_id", "app001");
			params.put("version", "v0.0.1");
			params.put("sign", "appSPOS_getPayStatus_sign");
			params.put("sub_deal_ssn", subDealSsn);
			params.put("order_id", orderId);
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统获取订单支付状态:"+params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/get_pay_status", params);
			if (logger.isInfoEnabled()) {
				logger.info("交易系统获取订单支付状态返回:" + map);
			}
			if(map == null) {
				getPayStatusVo.setResp_status("9999");
				getPayStatusVo.setMsg("交易系统获取订单支付状态返回空");
				return getPayStatusVo;
			}
			String[] resTip = ResourceMap.getArray("T_get_pay_status_" + (String) map.get("resp_status"));
			getPayStatusVo.setResp_status(resTip[0]);
			getPayStatusVo.setMsg(resTip[1]);
			getPayStatusVo.setSub_deal_ssn((String)map.get("sub_deal_ssn"));
			getPayStatusVo.setSub_deal_stauts((String)map.get("sub_deal_stauts"));
			getPayStatusVo.setSign("appSPOS_sign");
			return getPayStatusVo;
		} catch (Exception e) {
			logger.error(this, e);
			return getPayStatusVo;
		}
	}

	/**
	 * 订单查询
	 */
	@Override
	public SearchOrderVo searchOrder(String token, String orderDateBegin,
			String orderDateEnd, String refundDateBegin, String refundDateEnd,
			String searchWord, String orderId, String orderStat,String isTip) {
		SearchOrderVo searchOrderVo = new SearchOrderVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("token",token);
			params.put("order_date_begin", orderDateBegin);
			params.put("order_date_end", orderDateEnd);
			params.put("refund_date_begin", refundDateBegin);
			params.put("refund_date_end", refundDateEnd);
			params.put("search_word", searchWord);
			params.put("order_id", orderId);
			params.put("order_stat", orderStat);
			params.put("isTip", isTip);
			params.put("sign", "appSPOS_searchOrder_sign");
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统查询订单:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/search_order", params);
			if(map == null) {
				searchOrderVo.setResp_status("9999");
				searchOrderVo.setMsg("调交易系统查询订单返回空");
				return searchOrderVo;
			}
			String[] resTip = ResourceMap.getArray("T_search_order_" + (String) map.get("resp_status"));
			searchOrderVo.setResp_status(resTip[0]);
			searchOrderVo.setMsg(resTip[1]);
			searchOrderVo.setResult_id((String)map.get("result_id"));
			searchOrderVo.setResult_quantity(Integer.parseInt((String) map.get("result_quantity")));
			searchOrderVo.setSign("appSPOS_searchOrder_sign");
			return searchOrderVo;
		} catch (Exception e) {
			logger.error(this, e);
			return searchOrderVo;
		}
	}

	/**
	 * 订单查询结果
	 */
	@Override
	public GetOrderResultVo getOrderResult(String token, String resultId,
			int page, int quantity) {
		GetOrderResultVo getOrderResultVo=new GetOrderResultVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("token",token);
			params.put("result_id", resultId);
			params.put("page", page);
			params.put("quantity", quantity);
			params.put("sign", "appSPOS_getOrderResult_sign");
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统订单查结果查看:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/get_order_result", params);
			if(map == null) {
				getOrderResultVo.setResp_status("9999");
				getOrderResultVo.setMsg("交易系统订单查结果查看返回空");
				return getOrderResultVo;
			}
			String[] resTip = ResourceMap.getArray("T_get_order_result_" + (String) map.get("resp_status"));
			getOrderResultVo.setResp_status(resTip[0]);
			getOrderResultVo.setMsg(resTip[1]);
			getOrderResultVo.setTrade(map.get("trade"));
			getOrderResultVo.setTrade_quantity((Integer)map.get("trade_quantity"));
			getOrderResultVo.setSign("appSPOS_sign");
			return getOrderResultVo;
		} catch (Exception e) {
			logger.error(this, e);
			return getOrderResultVo;
		}
	}
	

	/**
	 * 订单退款查询结果
	 */
	@Override
	public GetOrderResultVo getOrderRefundResult(String token, String resultId,
			int page, int quantity) {
		GetOrderResultVo getOrderResultVo=new GetOrderResultVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("token",token);
			params.put("result_id", resultId);
			params.put("page", page);
			params.put("quantity", quantity);
			params.put("sign", "appSPOS_getOrderRefundResult_sign");
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统订单查结果查看:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/get_order_refund_result", params);
			if(map == null) {
				getOrderResultVo.setResp_status("9999");
				getOrderResultVo.setMsg("交易系统订单查结果查看返回空");
				return getOrderResultVo;
			}
			String[] resTip = ResourceMap.getArray("T_get_order_result_" + (String) map.get("resp_status"));
			getOrderResultVo.setResp_status(resTip[0]);
			getOrderResultVo.setMsg(resTip[1]);
			getOrderResultVo.setTrade(map.get("trade"));
			getOrderResultVo.setTrade_quantity(Integer.parseInt((String) map.get("trade_quantity")));
			getOrderResultVo.setSign("appSPOS_sign");
			return getOrderResultVo;
		} catch (Exception e) {
			logger.error(this, e);
			return getOrderResultVo;
		}
	}

	/**
	 * 订单明细补全
	 */
	@SuppressWarnings("unchecked")
	@Override
	public UpdOrderInfoVo updOrderInfo(String token, String orderId,
			String detail, String content, String comment) {
		UpdOrderInfoVo updOrderInfoVo = new UpdOrderInfoVo();
		try {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", token);
			params.put("order_id", orderId);
			params.put("detail", detail);
			params.put("content", content);
			params.put("comment", "comment");
			params.put("sign", "appSPOS_createRefund_sign");
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统更改商品明细:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/upder_OrderDataInfo",params);
			if (map == null) {
				updOrderInfoVo.setResp_status("9999");
				updOrderInfoVo.setMsg("交易系统订单查结果查看返回空");
				return updOrderInfoVo;
			}
			updOrderInfoVo.setMsg((String) map.get("msg"));
			updOrderInfoVo.setResp_status((String) map.get("resp_status"));
			int trade_quantity = Integer.parseInt(String.valueOf(map.get("trade_quantity")));
			updOrderInfoVo.setTrade_quantity(trade_quantity);
			updOrderInfoVo.setTrade((List<Trade>) map.get("trade"));
			updOrderInfoVo.setSign("appSPOS_updOrderInfo_sign");
		} catch (Exception e) {
			logger.error(this, e);
			return updOrderInfoVo;
		}
		return updOrderInfoVo;
	}

	/**
	 * 申请退款
	 */
	public CreateRefundVo createRefund(String token, String orderId,
			int refundFee, String comment, String operatorId, String operatorName) {
		CreateRefundVo createRefundVo = new CreateRefundVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("module_id", "app001");
			params.put("version", "v0.0.1");
			params.put("sign", "appSPOS_createRefund_sign");
			params.put("order_id", orderId);
			params.put("refund_fee", ""+refundFee);
			params.put("comment", comment);
			params.put("operator_id", operatorId);
			params.put("operator_name", operatorName);
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统申请退款:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/create_refund", params);
			if (logger.isInfoEnabled()) {
				logger.info("交易系统申请退款返回:" + map);
			}
			if(map == null) {
				createRefundVo.setResp_status("9999");
				createRefundVo.setMsg("交易系统申请退款返回空");
				return createRefundVo;
			}
			String[] resTip = ResourceMap.getArray("T_create_refund_" + (String) map.get("resp_status"));
			createRefundVo.setResp_status(resTip[0]);
			createRefundVo.setMsg(resTip[1]);
			createRefundVo.setSign("appSPOS_sign");
			return createRefundVo;
		} catch (Exception e) {
			logger.error(this, e);
			return createRefundVo;
		}
	}

	/**
	 * 退款复核
	 */
	@Override
	public AllowRefundVo allowRefund(String token, String orderId, int refundFee,
			String comment, String operatorId, String operatorName) {
		AllowRefundVo allowRefund = new AllowRefundVo();
		try {
			HashMap<String, Object> params = new HashMap<>();
			params.put("module_id", "app001");
			params.put("version", "v0.0.1");
			params.put("sign", "appSPOS_allowRefund_sign");
			params.put("order_id", orderId);
			params.put("refund_fee", ""+refundFee);
			params.put("comment", comment);
			params.put("operator_id", operatorId);
			params.put("operator_name", operatorName);
			if (logger.isInfoEnabled()) {
				logger.info("调交易系统退款复核:" + params);
			}
			Map<String, Object> map = HttpClient.getInstance()
					.doPOSTgetHashMap("/transSystem/allow_refund",params);
			if (logger.isInfoEnabled()) {
				logger.info("交易系统退款复核返回:" + map);
			}
			if(map == null) {
				allowRefund.setResp_status("9999");
				allowRefund.setMsg("交易系统退款复核返回空");
				return allowRefund;
			}
			String[] resTip = ResourceMap.getArray("T_allow_refund_" + (String) map.get("resp_status"));
			allowRefund.setResp_status(resTip[0]);
			allowRefund.setMsg(resTip[1]);
			allowRefund.setSign("appSPOS_sign");
			return allowRefund;
		} catch (Exception e) {
			logger.error(this, e);
			return allowRefund;
		}
	}

}
